import { DataString, empty } from "../data.mts";

const query = (stor: Storage) => {
  let result = 0;
  const count = stor.length;
  const data: Record<string, string> = {};
  for (let index = 0; index < count; ++index) {
    const key = stor.key(index);
    if (key) {
      const value = stor.getItem(key);
      result += key.length + (value?.length ?? 0);
      data[key] = value ?? empty;
    }
  }
  return Promise.resolve({ count, result, data });
};

const clear = (stor: Storage) => {
  stor.clear();
  return Promise.resolve();
};

const change = (stor: Storage, key: string, value?: string) => {
  value === undefined ? stor.removeItem(key) : stor.setItem(key, value);
  return Promise.resolve();
};

const summary = (
  storName: DataString.lStor | DataString.sStor,
  data: Awaited<ReturnType<typeof query>>,
) => `${storName}：
数量 ${String(data.count)}
大小 ${String(data.result)}`;

const stringify = (data: Awaited<ReturnType<typeof query>>) => {
  let prompts = "";
  for (const key of Object.keys(data.data)) {
    prompts += `------
键：${key}
值：${data.data[key] ?? ""}
`;
  }
  return prompts;
};

export default { query, clear, change, summary, stringify };
